<template>
  <map show-location="true" id="mymap" style="width: 100vw; height: 100vh" :circles="circlesBack"
    :polygons="polygonBack" :longitude="lng" :latitude="lat" :include-points='incPoints' show-compass="ture"
    enable-overlooking="ture" enable-rotate="ture" enable-zoom="ture" enable-scroll="ture"></map>
</template>

<script>
  import { getCorpAreaConfig, addWaybillgps, addViolation } from '@/api/me.js';
  import { parseTime } from '@/utils/ruoyi';
  import { authIsPass } from '@/utils/common';
  //先获取经纬度，然后再根据经纬度通过腾讯地图获取地址名称

  export default {
    name: 'map-com',
    props: {
      itemData: {}
    },
    data() {
      return {
        interval: '',
        isPdDistance: true,
        isJtDistance: true,
        pdData: [],
        jtData: [],
        lat: '',
        lng: '',
        incPoints: [],
        mapCtx: null,
        markers: [
          {
            iconPath: '',
            id: 0,
            latitude: 34.26703,
            longitude: 108.9402,
            width: 30,
            height: 30
          }
        ],
        polygonBack: [],
        polygons: [
          {
            //多边形的坐标数组
            points: [],
            fillColor: "#1B84D055", //填充颜色
            strokeColor: "#1B84D0", //描边颜色
            strokeWidth: 1, //描边宽度
            zIndex: 1, //层级
          },
          {
            //多边形的坐标数组
            points: [],
            fillColor: "#E50B2555", //填充颜色
            strokeColor: "#E50B25", //描边颜色
            strokeWidth: 1, //描边宽度
            zIndex: 1, //层级
          }
        ],
        circlesBack: [],
        circles: [
          {
            longitude: '', // PAIDUI
            latitude: '',
            fillColor: '#1B84D055',// 多边形填充颜色
            color: '#1B84D0',
            radius: '',
          },
          {
            longitude: '', //JINTING
            latitude: '',
            fillColor: '#E50B2555',// 多边形填充颜色
            color: '#E50B25',
            radius: '',
            level: 'abovelabels'
          }
        ],
        firstTime: true,
        // 位置上报信息
        LocationReportingInfo: {
          waybillNo: '',
          vehicleNo: '',
          gpsTime: null,
          rcvTime: null,
          lon: 0,
          lat: 0
        }
      };
    },

    methods: {
      async setLocationAuth() {
        // const { locationEnabled } = uni.getSystemInfoSync()
        // if (!locationEnabled) {
        //   uni.showToast({
        //     title: '该功能需要手机定位，请打开手机定位后重新进入！',
        //   })
        //   return
        // }
        const flag = await authIsPass('scope.userLocation')
        if (!flag) {
          uni.authorize({
            scope: 'scope.userLocation',
            fail: (res) => {
              uni.showModal({
                title: '检测到您没打开此小程序的定位权限，无法排号，前往设置打开？',
                showCancel: false,
                success: ({ confirm }) => {
                  if (confirm) {
                    uni.openSetting()
                  }
                },
              })
            }
          })
          return
        }
      },
      includePoints() {
        var that = this;
        that.mapCtx.includePoints({
          padding: [70],
          points: that.incPoints
        })
      },
      //清除定时器
      clearInterval() {
        if (this.interval) {
          clearInterval(this.interval)
          this.interval = null
        }
      },
      //格式化时间
      parseTime(time) {
        return parseTime(time);
      },
      // 上报位置信息
      async sendWaybillGPS(data) {
        try {
          let res = await addWaybillgps(data);
          if (res.code == 0) {
            console.log('addWaybillgps: ', res);
          }
        } catch (e) {
          return false;
        }
      },
      // 计算两点之间位置
      getDistanceInKM(lat1, lon1, lat2, lon2) {
        if (lat1 === lat2 && lon1 === lon2) return 0;
        const radlat1 = (Math.PI * lat1) / 180,
          radlat2 = (Math.PI * lat2) / 180,
          theta = lon1 - lon2;
        const radtheta = (Math.PI * theta) / 180;
        let dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        if (dist > 1) dist = 1;
        dist = Math.acos(dist);
        dist = (dist * 180) / Math.PI;
        dist = dist * 60 * 1.1515;
        dist = dist * 1.609344;
        return dist;
      },
      inAreaOrNot(point, path) {
        // let point = marker.getPosition();
        let isPointInRing = AMap.GeometryUtil.isPointInRing(point, path);
        return (isPointInRing ? true : false)
      },
      // 判断点是否在多边形范围内
      isPointInPolygon(lng, lat, polygon) {
        var cnt = 0;
        for (var i = 0; i < polygon.length; i++) {
          const g = lng;
          const t = lat;
          const p1g = polygon[i].longitude;
          const p1t = polygon[i].latitude;
          const p2g = polygon[i === polygon.length - 1 ? 0 : i + 1].longitude;
          const p2t = polygon[i === polygon.length - 1 ? 0 : i + 1].latitude;
          const ming = Math.min(p1g, p2g);
          const maxg = Math.max(p1g, p2g);
          const mint = Math.min(p1t, p2t);
          const maxt = Math.max(p1t, p2t);
          if ((mint <= t && t <= maxt && ming <= g) && (maxg <= g || (p2g + (p1g - p2g) * ((t - p2t) / (p1t -
            p2t)) < g))) {
            cnt++
          }
        }
        return cnt % 2 === 1;
      },
      async getAreaConfig() {
        //获取区域配置
        try {
          let res = await getCorpAreaConfig({ queueType: uni.getStorageSync('orderType') });
          if (res.code == 0) {
            this.pdData = res.data.filter((item) => item.regionType == 1);
            this.jtData = res.data.filter((item) => item.regionType == 2);

            if (this.pdData[0]?.fenceType == 1) {
              //circle
              this.lng = this.pdData[0]?.lonLat?.split(',')[0];
              this.lat = this.pdData[0]?.lonLat?.split(',')[1];
              this.circles[0].longitude = this.pdData[0]?.lonLat?.split(',')[0];
              this.circles[0].latitude = this.pdData[0]?.lonLat?.split(',')[1];
              this.circles[0].radius = this.pdData[0].radius;

              this.circlesBack.push(this.circles[0])
            } else {
              //polygon
              let lngs = this.pdData[0]?.lonLat?.split(';');

              let lnglat = []
              this.lng = lngs[0]?.split(',')[0];
              this.lat = lngs[0]?.split(',')[1];
              lngs.forEach((item, index) => {
                if (index < (lngs.length - 1)) {
                  lnglat.push({
                    "longitude": Number(item.split(',')[0]),
                    "latitude": Number(item.split(',')[1])
                  })
                }
              })
              this.polygons[0].points = lnglat
              this.polygonBack.push(this.polygons[0])
            }

            if (this.jtData[0]?.fenceType == 1) {
              //circle
              this.circles[1].longitude = this.jtData[0]?.lonLat?.split(',')[0];
              this.circles[1].latitude = this.jtData[0]?.lonLat?.split(',')[1];
              this.circles[1].radius = this.jtData[0].radius;
              this.circlesBack.push(this.circles[1])
            } else {
              //polygon
              let lngs = this.jtData[0]?.lonLat?.split(';');
              let lnglat = []
              this.lng = lngs[0]?.split(',')[0];
              this.lat = lngs[0]?.split(',')[1];
              lngs.forEach((item, index) => {
                if (index < (lngs.length - 1)) {
                  lnglat.push({
                    "longitude": Number(item.split(',')[0]),
                    "latitude": Number(item.split(',')[1])
                  })
                }
              })
              this.polygons[1].points = lnglat
              this.polygonBack.push(this.polygons[1])
            }
            this.incPoints.push({ 'latitude': this.lat, 'longitude': this.lng })
            this.getLocations();
            this.includePoints()
          }
        } catch (e) {
          return false;
        }
      },
      getLocations() {
        if (!uni.getStorageSync('checkPositionOrNullFlag')) {
          console.log('接单不校验位置');
          return;
        }
        // 获取用户实时位置
        const that = this;
        this.LocationReportingInfo.waybillNo = this.itemData.waybillRespVO?.waybillNo;
        this.LocationReportingInfo.vehicleNo = this.itemData.waybillRespVO?.vehicleNo;
        this.LocationReportingInfo.gpsTime = parseTime(new Date());
        uni.getLocation({
          //只能获取到经纬度
          type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回国测局坐标
          geocode: true, //设置该参数为true可直接获取经纬度及城市信息
          isHighAccuracy: true, // 开启高精度定位 微信小程序 (基础库 2.9.0+)
          highAccuracyExpireTime: 3000,
          success(res) {
            let longitude = res.longitude;
            let latitude = res.latitude;
            if (that.firstTime) {
              that.incPoints.push({ 'latitude': latitude, 'longitude': longitude })
              that.firstTime = false
            }
            that.LocationReportingInfo.lon = longitude;
            that.LocationReportingInfo.lat = latitude;
            that.LocationReportingInfo.rcvTime = parseTime(new Date());

            //计算当前位置距离区域中心点位置
            let pdDistance = that.getDistanceInKM(that.LocationReportingInfo.lat, that.LocationReportingInfo.lon, that.circles[0].latitude, that.circles[0].longitude);
            let jtDistance = that.getDistanceInKM(that.LocationReportingInfo.lat, that.LocationReportingInfo.lon, that.circles[1].latitude, that.circles[1].longitude);

            //判断是否在排队区域
            let isPdDistance = true;
            if (that.pdData[0]?.fenceType == 1) {
              //circle
              that.isPdDistance = (pdDistance < that.circles[0].radius / 1000) ? true : false
            } else {
              //polygon
              that.isPdDistance = that.isPointInPolygon(longitude, latitude, that.polygons[0].points)
            }
            //判断是否在禁停区域
            if (that.jtData[0]?.fenceType == 1) {
              //circle
              that.isJtDistance = (jtDistance < that.circles[1].radius / 1000) ? true : false
            } else {
              //polygon
              that.isJtDistance = that.isPointInPolygon(longitude, latitude, that.polygons[1].points)
            }
            let disStatus = {
              isPdDistance: that.isPdDistance,
              isJtDistance: that.isJtDistance
            };

            // 发射父组件位置信息
            if (that.itemData.waybillRespVO.waybillNo <= 40030) {
              that.$emit('isDisStatus', disStatus);
            }

            //上报位置信息 未完成运单才上报位置
            if (that.itemData.waybillRespVO.waybillStatus < 40050
              && (!!that.LocationReportingInfo.vehicleNo)
              && (!!that.LocationReportingInfo.waybillNo)) {
              that.sendWaybillGPS(that.LocationReportingInfo);
            }
          },
          fail(err) {
            console.log(err.errMsg)
          }
        });
      }
    },
    created() {
      if (uni.getStorageSync('orderType')) {
        this.getAreaConfig();
      }
      this.mapCtx = wx.createMapContext('mymap');
      this.setLocationAuth()
      this.interval = setInterval(() => {
        this.getLocations();
      }, 30000);
    },
    onHide() {
      this.clearInterval()
    },
    destroyed() {
      this.clearInterval()
    },
  };
</script>
<style lang="scss" scoped></style>